package com.geekstudy.week3;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

public class HttpRouterTool {

    final String Sequence = "sequence";
    final String Random = "random";

    int sequenceNumber = 1;

    public String routerUrlByRandom(String serverName, String url) {
        String responseText = null;
        Map<String, List<String>> serverUrlMap = getServerMap(Random);
        if(serverUrlMap.containsKey(serverName)) {
            List<String> urlList = serverUrlMap.get(serverName);
            int index = ThreadLocalRandom.current().nextInt(urlList.size()) - 1;
            String serverUrl = urlList.get(index);
            HttpTool httpTool = new HttpTool();
            responseText = httpTool.get(serverUrl + url);
        }
        return responseText;
    }

    public String routerUrlBySequence(String serverName, String url) {
        String responseText = null;
        Map<String, List<String>> serverUrlMap = getServerMap(Sequence);
        if(serverUrlMap.containsKey(serverName)) {
            List<String> urlList = serverUrlMap.get(serverName);
            int index =  (sequenceNumber - 1) % urlList.size();
            sequenceNumber++;

            String serverUrl = urlList.get(index);
            HttpTool httpTool = new HttpTool();
            responseText = httpTool.get(serverUrl + url);
        }

        return responseText;
    }

    private Map<String, List<String>> getServerMap(String type) {
        Map<String, List<String>> serverMap = new LinkedHashMap<String, List<String>>();

        List<String> week3UrlList = new ArrayList<String>();
        for(int size = 1; size <= 3; size++) {
            week3UrlList.add("http://127.0.0.1:9003/week3/" + type + "_" + size);
        }
        serverMap.put("week3", week3UrlList);

        return serverMap;
    }
}
